package sf.database.jdbc.sql;

import sf.database.jdbc.rowmapper.RowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * 类似JdbcTemplae中的类
 * @param <T>
 */
public class ResultSetSpliterator<T> implements Spliterator<T> {

    private final ResultSet rs;
    private ResultSetMetaData rsmd;
    private final RowMapper<T> rowMapper;

    private int rowNum = 0;

    public ResultSetSpliterator(ResultSet rs, RowMapper<T> rowMapper) {
        this.rs = rs;
        this.rowMapper = rowMapper;
        if (rs != null) {
            try {
                this.rsmd = rs.getMetaData();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            if (this.rs.next()) {
                action.accept(this.rowMapper.handle(this.rs, rsmd, this.rowNum++));
                return true;
            }
            return false;
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Spliterator<T> trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return Long.MAX_VALUE;
    }

    @Override
    public int characteristics() {
        return Spliterator.ORDERED;
    }

    public Stream<T> stream() {
        return StreamSupport.stream(this, false);
    }
}
